<template>
  <section class="grant-main">
    <el-collapse-transition>
      <section class="main-search merge">
        <span class="svg-container">
          <svg-icon icon-class="search" />
        </span>
        <el-input v-model.trim="listQuery.giveName" placeholder="输入福利名称搜索" class="search-input" @keyup.enter.native="handleFilter" />
        <section class="search-btn">
          <el-button class="filter-item" type="primary" @click="handleFilter">搜索</el-button>
          <el-button type="primary" @click="handleReset">重置</el-button>
        </section>
      </section>
    </el-collapse-transition>

    <section class="main-buttons">
      <section class="main-buttons-title">
        <span>自有商城福利配置</span>
      </section>
      <section class="main-buttons-btns">
        <el-button style="margin-left: 10px" @click="handleCreate">新建</el-button>
      </section>
    </section>

    <section class="main-tab">
     <el-tabs v-model="active" @tab-click="handleTabClick">
        <el-tab-pane v-for="item in types" :key="item.id" :label="item.name" :name="item.id" />
      </el-tabs>
		<!-- 	<div class="tabs">
				<div @click="handleTabClick2(item)" v-for="(item,index) in types" :key="item.id" class="tabItem" :class="{'choose':active==item.id,'leng':item.name.length>5} ">{{item.name}}</div>
			</div> -->
		</section>

    <section class="main-table">
      <v-table :list="list" :tag="pageType" :list-loading="listLoading" :filter-column="filtercolumn" @handleSelectionChange="handleSelectionChange">
        <el-table-column label="操作" fixed="right" align="center" min-width="100" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="handleStatus(scope.row)">{{ scope.row.publishStatus == "GIPSTSTUS01" ? "取消发布" : "发布" }}</el-button>
            <el-button type="text" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button type="text" size="mini" @click="handleDelete(scope.row.id)">删除</el-button>
            <el-button type="text" size="mini" @click="handleUser(scope.row)">人员设置</el-button>
						<el-button type="text" size="mini" @click="handleStatistics(scope.row)">活动统计</el-button>
					</template>
        </el-table-column>
      </v-table>

      <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

      <el-dialog v-el-drag-dialog :destroy-on-close="true" :visible.sync="visible" :close-on-click-modal="false" title="新建/编辑福利发放" center width="830px">
        <el-form ref="form" :model="form" :rules="rules" label-width="180px" style="height: 470px">
          <el-form-item label="发放名称" prop="giveName">
            <el-input v-model.trim="form.giveName" placeholder="请输入发放名称" />
          </el-form-item>
          <el-form-item v-show="state == 'create' " label="福利类型" prop="classifType">
            <el-radio-group v-model="form.classifType" @change="changeType">
              <el-radio v-for="(item, index) in types" :key="index" :label="item.id">{{ item.name }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <template v-if="form.classifType === '3'">
						<el-form-item label="商城专区" prop="dataId">
						  <el-select :disabled="state!='create'" v-model="form.dataId" placeholder="请选择" style="width: 100%" @change="zychange($event,'subacnttp')">
						    <el-option v-for="(item, index) in zyAcc" :key="index" :label="item.label" :value="item.value" />
						  </el-select>
						</el-form-item>
            <el-form-item label="出金账户" prop="accountId">
              <el-select :disabled="state!='create'" v-model="form.accountId" placeholder="请选择" style="width: 100%" @change="handleAccChange($event,'PURPOSE_ZYSC')">
                <el-option v-for="(item, index) in accList" :key="index" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="充值记录" prop="rechargeId">
              <el-select :disabled="state!='create'" v-model="form.rechargeId" placeholder="请选择" style="width: 100%" >
                <el-option v-for="(item, index) in rechList" :key="index" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item> 
            <el-form-item  label="职工福利子账户类型" prop="classifType2">
              <el-select disabled v-model="form.classifType2" placeholder="请选择" style="width: 100%" @change="handleAccountChange">
                <el-option v-for="(item, index) in accounts" :key="index" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
           <!-- <el-form-item label="是否支持福利金帐号" prop="isWelfarePay">
              <el-radio-group v-model="form.isWelfarePay">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item> -->
            <el-form-item label="定向发放金额(每人)上限" prop="userUpperLimit">
              <el-input v-model="form.userUpperLimit"  @blur="myBlur"  oninput="value=value.replace(/^\.+|[^\d.]/g,'')"  placeholder="请输入定向发放金额(每人)上限" >
								<template slot="append">元</template>
								</el-input>
            </el-form-item>
            <el-form-item label="福利领取起止时间" required>
              <el-col :span="11">
                <el-form-item label prop="receiveStarttime">
                  <el-date-picker v-model="form.receiveStarttime" type="datetime" placeholder="选择开始日期" style="width: 100%" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" />
                </el-form-item>
              </el-col>
              <el-col style="text-align: center" :span="2">-</el-col>
              <el-col :span="11">
                <el-form-item label prop="receiveEndtime">
                  <el-date-picker v-model="form.receiveEndtime" type="datetime" placeholder="选择结束日期" style="width: 100%" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" />
                </el-form-item>
              </el-col>
            </el-form-item>
            <el-form-item label="福利使用起止时间" required>
              <el-col :span="8">
                <el-form-item label prop="expirationStartdate">
                  <el-date-picker
                    v-model="form.expirationStartdate"
                    :disabled="fit"
                    type="datetime"
                    placeholder="选择开始日期"
                    style="width: 100%"
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
                  />
                </el-form-item>
              </el-col>
              <el-col style="text-align: center" :span="1">-</el-col>
              <el-col :span="8">
                <el-form-item label prop="expirationDate">
                  <el-date-picker v-model="form.expirationDate" :disabled="fit" type="datetime" placeholder="选择结束日期" style="width: 100%" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" />
                </el-form-item>
              </el-col>
              <el-col style="text-align: center" :span="7">
                <el-checkbox v-model="fit" @change="setEqualTime">与福利领取时间一致</el-checkbox>
              </el-col>
            </el-form-item>
          </template>
					<template v-if="form.classifType === '6'">
						<el-form-item  label="福利包" prop="dataId">
						  <el-select :disabled="state!='create'" v-model="form.dataId" placeholder="请选择" style="width: 100%" @change="zychange($event,'accountType')">
						    <el-option v-for="(item, index) in couponsList" :key="index" :label="item.label" :value="item.value" />
						  </el-select>
						</el-form-item>
					  <el-form-item label="出金账户" prop="accountId">
					    <el-select :disabled="state!='create'" v-model="form.accountId" placeholder="请选择" style="width: 100%" @change="handleAccChange($event,'PURPOSE_XXXJ')">
					      <el-option v-for="(item, index) in accList" :key="index" :label="item.label" :value="item.value" />
					    </el-select>
					  </el-form-item>
					  <el-form-item label="充值记录" prop="rechargeId">
					    <el-select :disabled="state!='create'" v-model="form.rechargeId" placeholder="请选择" style="width: 100%" >
					      <el-option v-for="(item, index) in rechList" :key="index" :label="item.label" :value="item.value" />
					    </el-select>
					  </el-form-item> 
					  <el-form-item  label="职工福利子账户类型" prop="classifType2">
					    <el-select disabled v-model="form.classifType2" placeholder="请选择" style="width: 100%" @change="handleAccountChange">
					      <el-option v-for="(item, index) in accounts" :key="index" :label="item.label" :value="item.value" />
					    </el-select>
					  </el-form-item>
					 <!-- <el-form-item label="是否支持福利金帐号" prop="isWelfarePay">
					    <el-radio-group v-model="form.isWelfarePay">
					      <el-radio :label="1">是</el-radio>
					      <el-radio :label="0">否</el-radio>
					    </el-radio-group>
					  </el-form-item> -->
					  <el-form-item label="定向发放金额(每人)上限" prop="userUpperLimit">
					    <el-input disabled v-model="form.userUpperLimit"  @blur="myBlur"  oninput="value=value.replace(/^\.+|[^\d.]/g,'')"  placeholder="请输入定向发放金额(每人)上限" >
								 <template slot="append">元</template>
							</el-input>
					  </el-form-item>
									
					  <el-form-item label="福利领取起止时间" required>
					    <el-col :span="11">
					      <el-form-item label prop="receiveStarttime">
					        <el-date-picker v-model="form.receiveStarttime" type="datetime" placeholder="选择开始日期" style="width: 100%" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" />
					      </el-form-item>
					    </el-col>
					    <el-col style="text-align: center" :span="2">-</el-col>
					    <el-col :span="11">
					      <el-form-item label prop="receiveEndtime">
					        <el-date-picker v-model="form.receiveEndtime" type="datetime" placeholder="选择结束日期" style="width: 100%" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" />
					      </el-form-item>
					    </el-col>
					  </el-form-item>
					  <el-form-item label="福利使用起止时间" required>
					    <el-col :span="8">
					      <el-form-item label prop="expirationStartdate">
					        <el-date-picker
					          v-model="form.expirationStartdate"
					          :disabled="fit"
					          type="datetime"
					          placeholder="选择开始日期"
					          style="width: 100%"
					          format="yyyy-MM-dd HH:mm:ss"
					          value-format="yyyy-MM-dd HH:mm:ss"
					        />
					      </el-form-item>
					    </el-col>
					    <el-col style="text-align: center" :span="1">-</el-col>
					    <el-col :span="8">
					      <el-form-item label prop="expirationDate">
					        <el-date-picker v-model="form.expirationDate" :disabled="fit" type="datetime" placeholder="选择结束日期" style="width: 100%" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" />
					      </el-form-item>
					    </el-col>
					    <el-col style="text-align: center" :span="7">
					      <el-checkbox v-model="fit" @change="setEqualTime">与福利领取时间一致</el-checkbox>
					    </el-col>
					  </el-form-item>
					</template>
          <template v-else-if="form.classifType != '3'  && form.classifType!=''">
            <el-form-item  label="兑换券" prop="classifType2">
              <el-select :disabled="state!='create'" v-model="form.classifType2" placeholder="请选择" style="width: 100%" @change="handleCouponsChange">
                <el-option v-for="(item, index) in couponsList" :key="index" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="兑换券领取起止时间" prop="receiveStarttime">
              <el-col :span="11">
                <el-form-item label prop="receiveStarttime">
                  <el-date-picker v-model="form.receiveStarttime" type="datetime" placeholder="选择开始日期" style="width: 100%" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" />
                </el-form-item>
              </el-col>
              <el-col style="text-align: center" :span="2">-</el-col>
              <el-col :span="11">
                <el-form-item label prop="receiveEndtime">
                  <el-date-picker v-model="form.receiveEndtime" type="datetime" placeholder="选择结束日期" style="width: 100%" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" />
                </el-form-item>
              </el-col>
            </el-form-item>
            <el-form-item label="兑换券使用起止时间" prop="expirationStartdate">
              <el-col :span="11">
                <el-form-item label prop="expirationStartdate">
                  <el-date-picker
                    disabled
                    v-model="form.expirationStartdate"
                    type="datetime"
                    placeholder="选择开始日期"
                    style="width: 100%"
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
                  />
                </el-form-item>
              </el-col>
              <el-col style="text-align: center" :span="2">-</el-col>
              <el-col :span="11">
                <el-form-item label prop="expirationDate">
                  <el-date-picker disabled v-model="form.expirationDate" type="datetime" placeholder="选择结束日期" style="width: 100%" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" />
                </el-form-item>
              </el-col>
            </el-form-item>
          </template>
				
          <el-form-item label="使用说明" prop="explain">
            <el-input v-model="form.explain" type="textarea" :autosize="{ minRows: 4, maxRows: 6 }" placeholder="请输入使用说明" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="default" style="padding: 10px 30px" @click="visible = false">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </div>
      </el-dialog>
    </section>
  </section>
</template>
<script>
import { int } from '@/utils/validate'
import Pagination from '@/components/Pagination'
import VTable from '@/components/Table'
import {getJdRech,queryJd,getRechOne, getRech,getDictByCode, queryPage, insert4Coupon, update4Account, update4Coupon, updatePublishStatus, get, del, queryAccount, queryCoupons,getAcc
 ,getSczq,getYhq,getZqInfo,getDhqInfo} from './../api/grant'
import permission from '@/directive/permission/index.js'
import elDragDialog from '@/directive/el-drag-dialog'
import ImageUpload from '@/components/ImageUpload'
import CryptoJS from '@/utils/aesJiaJM'
export default {
  name: 'GrantMain',
  components: { Pagination, VTable, ImageUpload },
  directives: { permission, elDragDialog },
  data() {
    return {
      i: '',
			zyAcc:[],
      listQuery: {
        page: 1,
        limit: 10,
        giveName: ''
      },
      list: [],
      accList:[],
      rechList:[],
      total: 0,
      listLoading: false,
      multipleSelection: [],
      visible: false,
      form: {
        id: '',
				dataId:'',
        accountId:'',
        rechargeId:'',
        giveName: '',
        userUpperLimit: '',
        classifType: '',
        classifType2: '',
        receiveStarttime: '',
        receiveEndtime: '',
        expirationStartdate: '',
        expirationDate: '',
        explain: '',
        // publishStatus: 'GIPSTSTUS02',
        areaName: '',
        areaImg: '',
        homeImg: '',
        isWelfarePay: 1,
			
      },
      rules: {
				dataId: [{ required: true, message: '请选择', trigger: 'change' }],
        classifType: [{ required: true, message: '请选择福利类型', trigger: 'blur' }],
        accountId: [{ required: true, message: '请选择出金账户', trigger: 'change' }],
        rechargeId : [{ required: true, message: '请选择充值记录', trigger: 'change' }],
        classifType2: [{ required: true, message: '请选择职工福利子账户类型', trigger: 'blur' }],
        receiveStarttime: [{ required: true, message: '请选择开始日期', trigger: 'blur' }],
        receiveEndtime: [{ required: true, message: '请选择结束日期', trigger: 'blur' }],
        giveName: [
          { required: true, message: '请输入发放名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        isWelfarePay: [
          { required: true, message: '请选择是否支持福利金帐号', trigger: 'blur' }
        ],
        userUpperLimit: [
          { required: true, message: '请输入定向发放金额(每人)上限', trigger: 'blur' },
          // { validator: int, trigger: 'blur' }
        ],
        explain: [{ required: true, message: '请填写使用说明', trigger: 'blur' }],
        expirationStartdate: [{ required: true, message: '请选择开始日期', trigger: 'blur' }],
        expirationDate: [{ required: true, message: '请选择结束日期', trigger: 'blur' }]
      },
      upload4area: {
        viewId: '',
        view: '/API-DOCUMENT/document/file/download?id=',
        imagecropperKey: 0
      },
      upload4home: {
        viewId: '',
        view: '/API-DOCUMENT/document/file/download?id=',
        imagecropperKey: 0
      },
      types: [
        {
          name: '福利包',
          id: '3'
        },
        {
          name: '兑换券',
          id: '4'
        }
				,
				{
				  name: '线下提货券',
				  id: '5'
				},
				{
				  name: '线下福利包',
				  id: '6'
				}
      ],
      accounts: [],
      couponsList: [],//兑换券列表
      active: '3',
      fit: true,
      state: 'create',
			pageType:'grantmain3'
    }
  },
  watch: {
		active(val){
			if(val=='3' || val=='6'){
				this.pageType="grantmain3"
			}else{
				this.pageType="grant3+"
			}
		},
    'form.receiveStarttime': {
      handler(newName, oldName) {
        if (this.form.classifType === '1') {
          return
        }
        if (newName && this.fit) {
          this.form.expirationStartdate = this.form.receiveStarttime
        }
      },
      immediate: true,
      deep: true
    },
    'form.receiveEndtime': {
      handler(newName, oldName) {
        if (this.form.classifType === '1') {
          return
        }
        if (newName && this.fit) {
          this.form.expirationDate = this.form.receiveEndtime
        }
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    if (this.$route.query.t) {
      this.active = this.$route.query.t
    }
    this.getList()
  },
  methods: {
		setEqualTime(val) {
			if(val) {
				this.form.expirationStartdate = this.form.receiveStarttime
				this.form.expirationDate = this.form.receiveEndtime
			}
		},
		handleStatistics(row){
			let fromObj={
				from:'/welfare/grants/haveconfig/index',
				t:this.active
			}
			// sessionStorage.setItem("curPath","/welfare/grants/haveconfig/")
			this.$router.push({
				path:this.$filterPath("activitystatistics"),
				query: {
					id: row.id,
					from: JSON.stringify(fromObj),
					c:row.classifType
				}
			})
		},
		zychange(e,t){
			let obj= this.zyAcc.find(item=>{
				return e==item.id
			})
			if(t=='accountType'){
				obj= this.couponsList.find(item=>{
					return e==item.id
				})
				this.$alert(`您选择的福利包是：${obj.name}，兑换券数量为：${obj.num}，审核状态为：${obj.status=='0'?'启用':'禁用'}，
				  ${obj.startTime ? '有效期是：' + this.formatTime(obj.startTime) + '至' : ''}
				  ${obj.endTime ? this.formatTime(obj.endTime) + ']' : ''}`, '提示', {
				    confirmButtonText: '确定',
				    callback: action => {
				      this.form.expirationStartdate = obj.startTime
				      this.form.receiveStarttime = obj.startTime
				      this.form.expirationDate = obj.endTime
				      this.form.receiveEndtime = obj.endTime
							this.form.userUpperLimit=obj.faceValue
				    }
				  })
			}
			let subObj=this.accounts.find(s=>{
			return obj[t]==s.value})
			if(subObj==undefined){
				this.$message.error("当前无可用职工福利子账户")
				this.form.classifType2=""
				return
			}
			this.form.classifType2=subObj.value
		},
		myBlur(e) {
		  this.form.userUpperLimit = e.target.value
		},
		dateFormat(fmt, date) {
			let ret
			const opt = {
				'y+': date.getFullYear().toString(), // 年
				'M+': (date.getMonth() + 1).toString(), // 月
				'd+': date.getDate().toString(), // 日
				'H+': date.getHours().toString(), // 时
				'm+': date.getMinutes().toString(), // 分
				's+': date.getSeconds().toString() // 秒
				// 有其他格式化字符需求可以继续添加，必须转化成字符串
			}
			for (const k in opt) {
				ret = new RegExp('(' + k + ')').exec(fmt)
				if (ret) {
					fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, '0')))
				}
			}
			return fmt
		},
  	/**
     * 切换福利类型
     */
   async changeType(val) {
		 this.rechList=[]
		 this.accList=[]
		 this.zyAcc=[]
			if(val=='3'){ //自有商城专区
				this.accList=await this.getAccFun()
				this.zyAcc = await this.getZyList()
				this.getAccounts().then((res) => {
				  if (res.length > 0) {
				  
				  } else {
				    this.$message({
				      title: '提示',
				      message: '当前无可用职工福利子账户，请前往【福利中心--商户子账号管理】创建职工福利子账户。',
				      type: 'error',
				      duration: 2000
				    })
				  }
				}).catch(err => {
				  console.log(err)
				})
			}else if(val=='4'){ //自有商城兑换券
				this.couponsList = await this.getCoupons(1,'')
			}else if(val=='5'){//线下实物兑换券
				this.couponsList = await this.getCoupons(2,1)
			}else if(val=='6'){//线下现金兑换券
				this.accList=await this.getAccFun()
				this.couponsList = await this.getCoupons(2,2)
				this.getAccounts().then((res) => {
				  if (res.length > 0) {
				  
				  } else {
				    this.$message({
				      title: '提示',
				      message: '当前无可用职工福利子账户，请前往【福利中心--商户子账号管理】创建职工福利子账户。',
				      type: 'error',
				      duration: 2000
				    })
				  }
				}).catch(err => {
				  console.log(err)
				})
			}
			const arr = ['id', 'giveName', 'classifType', 'explain']
			for (const i in this.form) {
			  if (arr.indexOf(i) === -1) {
			    this.form[i] = ''
			  }
			}
			this.fit = val !== '1'
			this.$nextTick(() => {
			  this.$refs['form'].clearValidate()
			})
		
    },
    filtercolumn(scope, item) {
      if (item === 'receiveTime') {
        return (scope.row['receiveStarttime'] && scope.row['receiveStarttime'].substring(0, 10)) + '至' + (scope.row['receiveEndtime'] && scope.row['receiveEndtime'].substring(0, 10))
      } else if (item === 'expirationTime') {
        let str = ''
        if (scope.row['expirationStartdate'] && scope.row['expirationStartdate'] != undefined) {
          str += scope.row['expirationStartdate'].substring(0, 10)
        }
        if (scope.row['expirationDate'] && scope.row['expirationDate'] != undefined) {
          str += '至' + scope.row['expirationDate'].substring(0, 10)
        }
        return str
      } else if (item === 'classifType2') {
        return scope.row[item] || '--'
      } else {
        return scope.row[item]
      }
    },

    /**
     * 选项卡切换
     */
    handleTabClick(tab, event) {
      this.listQuery.page = 1
      this.getList()
    },
		// /**
		//  * 选项卡切换2
		//  */
		// handleTabClick2(item) {
		// 	this.active=item.id
		//   this.listQuery.page = 1
		//   this.getList()
		// },

    handleSelectionChange(arr) {
      this.multipleSelection = arr
    },

    handleAccountChange(value) {
      const obj = this.accounts.find(a => a.subAcntTp === value)
      this.$alert(`您选择的职工福利子账户是：${obj.subAcntNm}，状态为：${obj.subAcntSt == 1 ? '禁用' : '启用'}，
        ${obj.subAcntStartTm ? '有效期是：' + this.formatTime(obj.subAcntStartTm) + '至' : ''}
        ${obj.subAcntEndTm ? this.formatTime(obj.subAcntEndTm) + ']' : ''}`, '提示', {
          confirmButtonText: '确定'
        })
    },
   async handleAccChange(val,t){
      this.form.rechargeId=""
      this.rechList= await this.getRechList(val,t)
    },
    handleCouponsChange(value) {
      const obj = this.couponsList.find(a => a.id === value)
      this.$alert(`您选择的兑换券是：${obj.name}，兑换券数量为：${obj.num}，审核状态为：${obj.status=='0'?'启用':'禁用'}，
        ${obj.startTime ? '有效期是：' + this.formatTime(obj.startTime) + '至' : ''}
        ${obj.endTime ? this.formatTime(obj.endTime) + ']' : ''}`, '提示', {
          confirmButtonText: '确定',
          callback: action => {
            this.form.expirationStartdate = obj.startTime
            this.form.receiveStarttime = obj.startTime
            this.form.expirationDate = obj.endTime
            this.form.receiveEndtime = obj.endTime
          }
        })
    },
    handleReset() {
      this.listQuery.page = 1
      this.listQuery.giveName = ''
      this.getList()
    },

    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },

     handleCreate() {
      for (const key in this.form) {
        if (key === 'publishStatus') {
          this.form[key] = 'GIPSTSTUS02'
        } else if (key === 'isWelfarePay') {
          this.form[key] = 1
        } else {
          this.form[key] = ''
        }
      }
      this.upload4home.viewId = ''
      this.upload4area.viewId = ''
			this.rechList=[]
			this.$nextTick(() => {
			  this.$refs.form.clearValidate()
			})
			this.state = 'create'
			this.visible = true
    },

    handleUpdate(row) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        get(row.id).then(async res => {
          loading.close()
          const data = res.data.data
          for (const key in this.form) {
              this.form[key] = data[key]
          }
					this.fit = this.form.receiveStarttime === this.form.expirationStartdate && this.form.receiveEndtime === this.form.expirationDate
					this.state = 'update'
					if(this.form.classifType=='3'){
						this.rechList= await this.getRechOneFun(this.form.rechargeId)
						this.accList=await this.getAccFun()
						this.zyAcc = await this.getZqFun(this.form.dataId)
						this.getAccounts().then(() => {
						  this.visible = true
						  this.$nextTick(() => {
						    this.$refs['form'].clearValidate()
						  })
						})
					}else if(this.form.classifType=='6'){
						this.couponsList= await this.getDhqFun(this.form.dataId)
						this.accList=await this.getAccFun()
						this.rechList= await this.getRechOneFun(this.form.rechargeId)
						this.getAccounts().then(() => {
						  this.visible = true
						  this.$nextTick(() => {
						    this.$refs['form'].clearValidate()
						  })
						})
					}
					else if(this.form.classifType!='3'){
						this.couponsList= await this.getDhqFun(this.form.classifType2)
						console.log('couponsList',this.couponsList)
						this.visible = true
					}
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },

    handleStatus(row) {
      const state = row.publishStatus === 'GIPSTSTUS01' ? 'GIPSTSTUS02' : 'GIPSTSTUS01'
      let msg = ''
      if (row.publishStatus === 'GIPSTSTUS01') {
        msg = '取消发布'
      } else {
        msg = '发布'
      }
      this.$confirm('确定' + msg + '该数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        })
        return new Promise((resolve, reject) => {
          updatePublishStatus({ id: row.id, publishStatus: state }).then(() => {
            loading.close()
            this.$message({
              title: '成功',
              message: msg + '成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }).catch(error => {
            loading.close()
            reject(error)
          })
        })
      }).catch(() => { })
    },

    handleUser(row) {
      this.$router.push({ path:this.$filterPath("user"), query: { id: row.id, t: this.active } })
    },

    handleCommodity(row) {
      this.$router.push({path:this.$filterPath("commodity"), query: { id: row.id, t: this.active } })
    },
		handleRefund(row){
			this.$router.push({path:this.$filterPath("refundList"), query: { id: row.id, t: this.active } })
		
		},

    handleDetail(row) {
      this.$router.push({path:this.$filterPath("detail")
	, query: { id: row.id, t: this.active } })
    },

    handleDelete(ids) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        })
        return new Promise((resolve, reject) => {
          del(ids).then(() => {
            loading.close()
            this.$message({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }).catch(error => {
            loading.close()
            reject(error)
          })
        })
      }).catch(() => { })
    },

    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code).then(res => {
          this.dict[code] = (res.data.data && res.data.data.length > 0) ? res.data.data[0].list : []
        }).catch(error => {
          reject(error)
        })
      })
    },

    formatTime(str) {
      return str && str.replace(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/, '$1-$2-$3 $4:$5:$6')
    },
	
    getRechList(id,t){
         const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        getRech({accountId:id ,purpose:t}).then(res => {
          loading.close()
          const arr = res.data.data || []
          resolve(arr.map(a => ({
            ...a,
            value: a.id,
            label: `${a.applyName}(${a.rechargeAmount}元)`
          })))
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    getRechOneFun(id){
        const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        getRechOne({rechargeId:id}).then(res => {
          loading.close()
          const arr = res.data.data || []
          resolve(arr.map(a => ({
            ...a,
            value: a.id,
            label: `${a.applyName}(${a.rechargeAmount}元)`
          })))
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
		getDhqFun(id){
			const loading = this.$loading({
			  lock: true,
			  text: '请稍后',
			  spinner: 'el-icon-loading',
			  background: 'rgba(0, 0, 0, 0.3)'
			})
			return new Promise((resolve, reject) => {
			  getDhqInfo({id:id }).then(res => {
			    loading.close()
			    const arr = [res.data.data]
			   let arr2= arr.map(a => ({
			      ...a,
			      value: a.id,
			      label: `${a.name}-${a.num}[${a.status=='0'?'启用':'禁用'}]${a.startTime ? '[' + this.formatTime(a.startTime) + '至' : ''}${a.endTime ? this.formatTime(a.endTime) + ']' : ''}`
			    }))
			    resolve(arr2)
			  }).catch(error => {
			    loading.close()
			    reject(error)
			  })
			})
		},
    getCoupons(type,style) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        queryCoupons({page:1,pageSize:1000,type:type,style:style }).then(res => {
          loading.close()
          const arr = res.data.data.rows || []
          resolve(arr.map(a => ({
            ...a,
            value: a.id,
            label: `${a.name}-${a.num}[${a.status=='0'?'启用':'禁用'}]${a.startTime ? '[' + this.formatTime(a.startTime) + '至' : ''}${a.endTime ? this.formatTime(a.endTime) + ']' : ''}`
          })))
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    getAccFun() {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        getAcc().then(res => {
          loading.close()
          const arr = res.data.data || []
          resolve(arr.map(a => ({
            ...a,
            value: a.id,
            label: `${a.name}(${CryptoJS.$aesJieM(a.accountNumber)})`
          })))
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
		getAccounts() {
		  const loading = this.$loading({
		    lock: true,
		    text: '请稍后',
		    spinner: 'el-icon-loading',
		    background: 'rgba(0, 0, 0, 0.3)'
		  })
		  return new Promise((resolve, reject) => {
		    queryAccount({ giveInfoId: this.form.id }).then(res => {
		      loading.close()
		      const arr = res.data.data || []
		      this.accounts = arr.map(a => ({
		        ...a,
		        value: a.subAcntTp,
		        label: `${a.subAcntTp}-${a.subAcntNm}[${a.subAcntSt == 1 ? '禁用' : '启用'}]${a.subAcntStartTm ? '[' + this.formatTime(a.subAcntStartTm) + '至' : ''}${a.subAcntEndTm ? this.formatTime(a.subAcntEndTm) + ']' : ''}`
		      }))
		      resolve(arr)
		    }).catch(error => {
		      loading.close()
		      reject(error)
		    })
		  })
		},
		getZqFun(id){
			const loading = this.$loading({
			  lock: true,
			  text: '请稍后',
			  spinner: 'el-icon-loading',
			  background: 'rgba(0, 0, 0, 0.3)'
			})
			return new Promise((resolve, reject) => {
			  getZqInfo({id:id }).then(res => {
			    loading.close()
			    const arr = [res.data.data]
			   let arr2= arr.map(a => ({
			      ...a,
			      value: a.id,
			      label: `${a.areaName}[${a.areaStatusName}]${a.areaStartTime ? '[' + this.formatTime(a.areaStartTime) + '至' : ''}${a.areaEndTime ? this.formatTime(a.areaEndTime) + ']' : ''}`
			    }))
			    resolve(arr2)
			  }).catch(error => {
			    loading.close()
			    reject(error)
			  })
			})
		},
    getZyList() {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        getSczq({ page: 1,pageSize:10000 }).then(res => {
          loading.close()
          const arr = res.data.data.rows|| []
					console.log(res.data.data)
          let zy = arr.map(a => ({
            ...a,
            value: a.id,
            label: `${a.areaName}[${a.areaStatusName}]${a.areaStartTime ? '[' + this.formatTime(a.areaStartTime) + '至' : ''}${a.areaEndTime ? this.formatTime(a.areaEndTime) + ']' : ''}`
          }))
          resolve(zy)
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    submit() {
      if (this.form.classifType === '3'|| this.form.classifType === '6') {
				if (new Date(this.form.receiveEndtime).getTime() < new Date().getTime()) {
					this.$message({
						message: '福利领取结束时间不得小于当前时间！',
						type: 'warning'
					})
					return
				}
				if (new Date(this.form.expirationDate).getTime() < new Date().getTime()) {
					this.$message({
						message: '福利使用结束时间不得小于当前时间！',
						type: 'warning'
					})
					return
				}
				if (new Date(this.form.receiveStarttime).getTime() > new Date(this.form.receiveEndtime).getTime()) {
					this.$message({
						message: '福利领取开始时间不得大于福利领取结束时间！',
						type: 'warning'
					})
					return
				}
				if (new Date(this.form.expirationStartdate).getTime() > new Date(this.form.expirationDate).getTime()) {
					this.$message({
						message: '福利使用开始时间不得大于福利使用结束时间！',
						type: 'warning'
					})
					return
				}
				if (new Date(this.form.expirationStartdate).getTime() < new Date(this.form.receiveStarttime).getTime()) {
					this.$message({
						message: '福利使用开始时间不得小于福利领取开始时间！',
						type: 'warning'
					})
					return
				}
				if (new Date(this.form.expirationDate).getTime() < new Date(this.form.expirationStartdate).getTime()) {
					this.$message({
						message: '福利使用结束时间不得小于福利领取结束时间！',
						type: 'warning'
					})
					return
				}
        this.state == 'create' ? this.createData4Accounts(this.form.classifType) : this.updateData4Accounts()
      } 
			else if(this.form.classifType != '3'){
				if(new Date(this.form.receiveEndtime).getTime() < new Date().getTime()) {
					this.$message({
						message: '兑换券领取结束时间不得小于当前时间！',
						type: 'warning'
					})
					return
				}
				if(new Date(this.form.expirationDate).getTime() < new Date().getTime()) {
					this.$message({
						message: '兑换券已过期，请选择其他兑换券！',
						type: 'warning'
					})
					return
				}
				this.form.userUpperLimit=1
        this.state == 'create' ? this.createData4Coupon(this.form.classifType) : this.updateData4Coupon()
      }

    },
    createData4Accounts() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          const params = Object.assign({}, this.form)
          return new Promise((resolve, reject) => {
            insert4Coupon(params).then(() => {
              this.dialogVisible = false
              loading.close()
              this.$message({
                title: '成功',
                message: '添加成功',
                type: 'success',
                duration: 2000
              })
              this.visible = false
							this.active=params.classifType
              this.getList()
            }).catch(error => {
              loading.close()
              reject(error)
            })
          })
        } else {
          return false
        }
      })
    },

    updateData4Accounts() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          const params = Object.assign({}, this.form)
          params['bigturntableId'] = this.id
          return new Promise((resolve, reject) => {
            update4Account(params).then(() => {
              loading.close()
              this.$message({
                title: '成功',
                message: '修改成功',
                type: 'success',
                duration: 2000
              })
              this.visible = false
              this.getList()
            }).catch(error => {
              loading.close()
              reject(error)
            })
          })
        } else {
          return false
        }
      })
    },

    createData4Coupon(type) {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (new Date(this.form.receiveEndtime).getTime() > new Date(this.form.expirationDate).getTime()) {
            this.$message({
              title: '提示',
              message: '兑换券领取结束时间不得大于兑换券使用结束时间',
              type: 'error',
              duration: 2000
            })
            return
          }
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          const params = Object.assign({}, this.form)
          return new Promise((resolve, reject) => {
            insert4Coupon(params,type).then(() => {
              this.dialogVisible = false
              loading.close()
              this.$message({
                title: '成功',
                message: '添加成功',
                type: 'success',
                duration: 2000
              })
              this.visible = false
							this.active=params.classifType
              this.getList()
            }).catch(error => {
              loading.close()
              reject(error)
            })
          })
        } else {
          return false
        }
      })
    },

    updateData4Coupon() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (new Date(this.form.receiveEndtime).getTime() > new Date(this.form.expirationDate).getTime()) {
            this.$message({
              title: '提示',
              message: '兑换券领取结束时间不得大于兑换券使用结束时间',
              type: 'error',
              duration: 2000
            })
            return
          }
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          const params = Object.assign({}, this.form)
          params['bigturntableId'] = this.id
          return new Promise((resolve, reject) => {
            update4Account(params).then(() => {
              loading.close()
              this.$message({
                title: '成功',
                message: '修改成功',
                type: 'success',
                duration: 2000
              })
              this.visible = false
              this.getList()
            }).catch(error => {
              loading.close()
              reject(error)
            })
          })
        } else {
          return false
        }
      })
    },
    getList(obj) {
      this.listLoading = true
      var query = {
        classifType: this.active,
        page: obj ? obj.page : this.listQuery.page,
        pageSize: obj ? obj.limit : this.listQuery.limit,
        giveName: this.listQuery.giveName
      }
      return new Promise((resolve, reject) => {
        queryPage(query).then(response => {
          this.list = response.data.data.rows
          this.total = response.data.data.total
          this.listLoading = false
        }).catch(error => {
          reject(error)
          this.listLoading = false
        })
      })
    }
  }
}
</script>
<style lang="scss">
@import '@/styles/mixin.scss';
.grant-main {
  padding: 10px;
  .main-search {
    background-color: #fff;
    padding: 0 10px;
    .svg-container {
      padding: 0 5px 0 10px;
      color: #bfced6;
      vertical-align: middle;
      display: inline-block;
    }
    .search-input {
      width: 60%;
      position: relative;
      &:after {
        content: '';
        position: absolute;
        left: -25px;
        right: 0;
        bottom: 8px;
        height: 1px;
        background: rgba(226, 227, 232, 1);
      }
      input {
        outline: none;
        background: transparent;
        border: none;
        outline: medium;
        padding: 0;
        &:focus {
          outline: none;
          background-color: transparent;
        }
      }
    }
    .search-btn {
      display: inline-block;
      float: right;
      .el-button.is-round {
        padding: 10px 30px;
        margin-right: 34px;
      }
      .search-more {
        font-size: 14px;
        font-weight: 500;
        @include font-color($mainColor);
        cursor: pointer;
        margin-left: 10px;
      }
    }

    &.merge {
      height: 50px;
      line-height: 50px;
    }
  }

  .main-buttons {
    display: flex;
    line-height: 36px;
    margin-top: 10px;
    .main-buttons-title {
      flex: 1;
      height: 36px;
      line-height: 36px;
      font-size: 16px;
      font-weight: bold;
      color: rgba(51, 51, 51, 1);
    }
  }

  .main-tab {
    width: 100%;
    margin-top: 10px;
    padding: 0 10px;
    background-color: #fff;
    display: flex;
    border-radius: 4px;
		// .tabs{
		// 	height: 60px;
		// 	display: flex;
		// 	font-family: Helvetica Neue,Helvetica,PingFang SC,Hiragino Sans GB,Microsoft YaHei,SimSun,sans-serif;
		// 	.tabItem{
		// 		 display: flex;
		// 		 align-items:center;
		// 		 height: 100%;
		// 		 margin-right: 20px;
		// 		 cursor: pointer;
		// 		 @include font-color($mainColor);
		// 		 &.leng{
		// 			 width: 70px;
		// 		 }
		// 		 &.choose{
		// 			 position: relative;
		// 			 height: 100%;
		// 			 &::before{
		// 					position: absolute;
		// 					content: '';
		// 					bottom: 0px;
		// 					left: 0;
		// 					right: 0;
		// 					top: 0;
		// 					border-bottom:2px solid $mainColor ;
		// 			 }
		// 		 }
				 
		// 	}
		// }
    .el-tabs__nav-wrap::after {
      display: none;
    }
    .el-tabs__header {
      margin: 0;
    }
  }

  .inner-explain {
    margin-top: 10px;
    line-height: 1.1;
    color: #999;
    font-size: 14px;
    display: flex;
    align-items: flex-start;
    > i {
      margin-right: 5px;
    }

    p {
      margin: 0;
      padding: 0;
      margin-bottom: 5px;
    }
  }
}
</style>
